//
//  Ugc_ReleaseFailure_MorePicCell_WX.m
//  ZITHER
//
//  Created by weixin on 2018/9/29.
//  Copyright © 2018年 weixn. All rights reserved.
//

#import "Ugc_ReleaseFailure_MorePicCell_WX.h"
#import "NetworkEngine+imageCloudManager.h"
#import "Ugc_ReleaseFailure_VC.h"

typedef void(^AskImageUploadBlock)(BOOL isSuccess, NSString *imageURLs);
@implementation Ugc_ReleaseFailure_MorePicCell_WX

- (void)awakeFromNib {
    [super awakeFromNib];
    [self setUI];
    [self setMasonry];
    self.userInteractionEnabled = YES;
    
}

-(void)setModel:(UgcReleaseFailureModel *)model
{
    _model = model;
    
    self.usercomment.text = model.content;
    
    if (model.arrMPic.count>0) {
        for (int i = 0; i<9; i++) {
            if (i<model.arrMPic.count) {
//                NSString *strpic= [NSString stringWithFormat:@"%@%@",RootUrlImage,model.arrMPic[i]];
                
//                [self.arrImageView[i] sd_setImageWithURL:[NSURL URLWithString:strpic] placeholderImage:[UIImage imageNamed:@"ucg_img_loding"]];
                self.arrImageView[i].image = model.arrMPic[i];
                self.arrImageView[i].hidden=NO;
            }else{
                self.arrImageView[i].hidden=YES;
            }
        }
    }else{
        for (int i = 0; i<9; i++) {
            self.arrImageView[i].image = [UIImage imageNamed:@"110"];
            self.arrImageView[i].hidden=YES;
        }
    }
    
    [self setIndexCell:model.arrMPic.count];
    [self layoutIfNeeded];
}





-(void)setMasonry{
    
    [self.usercomment mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self).offset(0);
        make.left.equalTo(self).offset(14);
        make.right.equalTo(self).offset(-14);
    }];
    
    [self.userPic mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.usercomment.mas_bottom).offset(10);
        make.left.equalTo(self).offset(14);
        make.right.equalTo(self).offset(-14);
        make.height.mas_equalTo(0);
    }];
    
    [self.resend mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.userPic.mas_bottom).offset(20);
        make.left.equalTo(self.del.mas_right).offset(50);
    }];
    
    [self.del mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.userPic.mas_bottom).offset(20);
        make.left.equalTo(self).offset(14);
    }];
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 1, 1)];
    view.backgroundColor = [UIColor colorWithHex:@"EEEEEE"];
    [self addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.del.mas_bottom).offset(25);
        make.left.right.equalTo(self).offset(0);
        make.height.mas_equalTo(1);
        make.bottom.equalTo(self).offset(-26);
    }];
    
    
    
}

-(void)setUI{
    [self addSubview:self.resend];
    [self addSubview:self.del];
    [self addSubview:self.usercomment];
    [self addSubview:self.userPic];
    for (UIImageView *imageView in self.arrImageView) {
        [self.userPic addSubview:imageView];
        
    }
}

-(void)setIndexCell:(NSInteger)indexCell
{
    if (indexCell==_indexCell) {
        return;
    }
    _indexCell = indexCell;
    
    
    if (indexCell == 0) {
        [self.userPic mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(0);
        }];
    }else if (indexCell == 1){
        [self.userPic mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo((kScreenW-90)/3.0*2);
        }];
    }else if (indexCell/4 < 1){
        [self.userPic mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(((kScreenW-90)/3.0-10));
        }];
    }else if (indexCell/7 < 1){
        [self.userPic mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(((kScreenW-90)/3.0)*2-10);
        }];
    }else{//(indexCell/3<=3)
        [self.userPic mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(((kScreenW-90)/3.0)*3-10);
        }];
    }
    [self layoutIfNeeded];
    
    //0:带文字,不带图片 1:不带文字,带图片 2:带图片,带文字
    //    [self addImage:indexCell];
    
}




-(QMUILabel *)usercomment{
    if (!_usercomment) {
        _usercomment = [[QMUILabel alloc]initWithFrame:CGRectMake(0, 0, 1, 1)];
        _usercomment.numberOfLines = 0;
        _usercomment.font = [UIFont systemFontOfSize:18];
    }
    return _usercomment;
}

-(UIView *)userPic{
    if (!_userPic) {
        _userPic = [[QMUILabel alloc]initWithFrame:CGRectMake(0, 0, 1, 1)];
        _userPic.userInteractionEnabled = YES;
    }
    return _userPic;
}





-(NSMutableArray *)arrImageView{
    if (!_arrImageView) {
        _arrImageView = [[NSMutableArray alloc]init];
        for (int i = 0; i<9; i++) {
            CGFloat imgHeight = (kScreenW-90)/3.0-10;
            UIImageView *imageV = [[UIImageView alloc]init];
            imageV.frame =  CGRectMake(i%3*(imgHeight+10), i/3*(imgHeight+10), imgHeight, imgHeight);
            imageV.hidden = YES;
            imageV.tag = i+100;
            imageV.contentMode = 2;
            NSString *str = [NSString stringWithFormat:@"%@%@",RootUrlImage,self.model.arrMPic[i]];
            [imageV sd_setImageWithURL:[NSURL URLWithString:str] placeholderImage:[UIImage imageNamed:@"ucg_img_loding"]];
            imageV.backgroundColor = [UIColor randomColor];
            
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
            __weak __typeof(self)weakSelf = self;
            [[tap rac_gestureSignal] subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
                if (weakSelf.showBigPic) {
                    weakSelf.showBigPic(weakSelf.indexPath,imageV.tag-100);
                }
            }];
            [imageV addGestureRecognizer:tap];
            imageV.userInteractionEnabled = YES;
            [imageV setCornerRadiusWithRadius:8 isMasks:YES];
            //            [self viewAddRounderCornerWithRadius:8 borderWidth:1 borderColor:[UIColor whiteColor] viewL:imageV];
            imageV.clipsToBounds = YES;
            [_arrImageView addObject:imageV];
        }
    }
    return _arrImageView;
}


/** 设置圆角和边框*/
- (void)viewAddRounderCornerWithRadius:(CGFloat)radius borderWidth:(CGFloat)width borderColor:(UIColor *)color viewL:(UIView*)view {
    
    UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, view.width, view.height) cornerRadius:radius];
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    
    if (radius != 0) {
        maskLayer.path = bezierPath.CGPath;
    }
    maskLayer.frame = CGRectMake(0, 0, view.width, view.height);
    
    if (width != 0 && color) {
        CAShapeLayer *borderLayer = [CAShapeLayer layer];
        borderLayer.frame = CGRectMake(0, 0, view.width, view.height);
        borderLayer.lineWidth = width;
        borderLayer.strokeColor = color.CGColor;
        borderLayer.fillColor = [UIColor clearColor].CGColor;
        borderLayer.path = bezierPath.CGPath;
        [self.layer insertSublayer:borderLayer atIndex:0];
    }
    [self.layer setMask:maskLayer];
}


-(QMUIButton *)resend{
    if (!_resend) {
        _resend = [[QMUIButton alloc]initWithFrame:CGRectMake(0, 0, 1, 1)];
        [_resend setTitle:@"重新发送" forState:UIControlStateNormal];
        [_resend setTitleColor:baseColorTheme forState:UIControlStateNormal];
        [_resend setCornerRadiusWithRadius:10 isMasks:YES];
//        [_resend setBorderWithColor:[UIColor blackColor] width:1];
        
        @weakify(self);
        [[_resend rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            [self send];
        }];
    }
    return _resend;
}

-(QMUIButton *)del{
    if (!_del) {
        _del = [[QMUIButton alloc]initWithFrame:CGRectMake(0, 0, 1, 1)];
        [_del setTitle:@"删除" forState:UIControlStateNormal];
        [_del setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
//        _del.backgroundColor = [UIColor redColor];
        [_del setCornerRadiusWithRadius:10 isMasks:YES];
        @weakify(self);
        [[_del rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            [kUSER_INFO_MANAGER delFailureModel:self.indexPath.row];
            [Tools showTips:@"删除成功"];
            Ugc_ReleaseFailure_VC *vc = (Ugc_ReleaseFailure_VC*)[self getViewController:[Ugc_ReleaseFailure_VC class]];
            
            [vc.tbv removeCell:self];
        }];
    }
    return _del;
}


-(void)send{
    
    //是否有图片
    if (self.model.arrMPic.count > 0) {
        //有图片  先上传图片
        
        [self uploadImageWithPhotos:self.model.arrMPic.copy completion:^(BOOL isSuccess, NSString *imageURLs) {
            if (isSuccess) {
                [Tools showTips:@"图片上传成功"];
                [kUSER_INFO_MANAGER delFailureModel:self.indexPath.row];
                Ugc_ReleaseFailure_VC *vc = (Ugc_ReleaseFailure_VC*)[self getViewController:[Ugc_ReleaseFailure_VC class]];
                
                [vc.tbv removeCell:self];
            } else {
                [Tools showTips:@"发送失败"];
            }
        }];
    }else{
        //没图片
        [[serviceDefualt loadGetAddUserUgc:self.model.content fileList:nil userSubjectId:self.model.topicID reponseObjctClass:nil]subscribeNext:^(ResponseData * x) {

//        [[serviceDefualt loadGetAddUserUgc:self.model.content fileList:nil reponseObjctClass:nil]subscribeNext:^(ResponseData * x) {
            
            if (x.success) {
                [Tools showTips:@"发送成功"];
                [kUSER_INFO_MANAGER delFailureModel:self.indexPath.row];
                Ugc_ReleaseFailure_VC *vc = (Ugc_ReleaseFailure_VC*)[self getViewController:[Ugc_ReleaseFailure_VC class]];
                
                [vc.tbv removeCell:self];
            }else{
                [Tools showTips:@"发送失败"];
            }
        }];
    }
}

#pragma mark - 上传图片
- (void)uploadImageWithPhotos:(NSArray<UIImage *> *)photos completion:(AskImageUploadBlock)completion {
    //  开启菊花
    [QMUITips showLoadingInView:self];
    // 调度组
    dispatch_group_t group = dispatch_group_create();
    // 队列
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    __block NSMutableArray<NSString *> *uploadURLs = @[].mutableCopy;
    for (NSUInteger i = 0; i< photos.count; i++) {
        UIImage *image = [photos objectAtIndex:i];
        //分别开组
        dispatch_group_enter(group);
        dispatch_group_async(group, queue, ^{
            NSString *date = [NSString currentDateDateFormatter:@"yyyyMM"];
            NSString *path =[NSString stringWithFormat:@"/ugc/%@",date];
            
            [kNetworkShared getImageURLWithImageOld:image Path:path batchIndex:i completion:^(COSObjectUploadTaskRsp *uploadTaskRsp, NSString *filePath, NSString *fileName, BOOL isSuccess, NSError *error) {
                if (isSuccess) {
                    [uploadURLs addObject:kSTRING_FORMAT(@"%@/%@",filePath, fileName)];
                }
                dispatch_group_leave(group);
            }];
            
        });
    }
    //完成通知
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [QMUITips hideAllTipsInView:self];
        if (uploadURLs.count == photos.count) {
            NSString *imgURLs = [uploadURLs componentsJoinedByString:@","];
            // 全部上传成功
            [[serviceDefualt loadGetAddUserUgc:self.model.content fileList:uploadURLs userSubjectId:self.model.topicID reponseObjctClass:nil]subscribeNext:^(ResponseData * x) {

//            [[serviceDefualt loadGetAddUserUgc:self.model.content fileList:uploadURLs reponseObjctClass:nil]subscribeNext:^(ResponseData * x) {
                if (x.success) {
                    if (completion) {
                        completion(YES, imgURLs);
                    }
                }else{
                    if (completion) {
                        completion(NO, nil);
                    }
                }
            }];
            
        } else {
            if (completion) {
                completion(NO, nil);
            }
        }
    });
}

@end
